package com.szholly.pro.watergas_server.common.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;

import com.szholly.pro.watergas_server.common.data.DataUtil;
import com.szholly.data.general.GlobalParameter;
import com.szholly.data.general.RowBase;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class WeChatHelper {	
	static Logger log;
	
	// 发送消息分组所有成员
	// private final static String TOPARTY = "@all";
	// 获取配置文件中的值
	private final static String CORPID = "wx410b0c8cea62aa15";// 需要自己申请，官网有试用企业号
	// 可以申请试用
	private final static String CORPSECRET = "AxDyAhUNCfnFRF3vn9_aMdMxAQrLdof3Vf06PraxNyXzqLZf8u6Xs-XI5aJClfWB";
	// 获取访问权限码URL
	private final static String ACCESS_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";
	// 创建会话请求URL
	private final static String CREATE_SESSION_URL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
	// 添加成员URL 
	private final static String ADD_MEMBER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=";
	// 更新成员URL
	private final static String UPDATE_MEMBER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=";
	// 更新成员URL
	private final static String DELETE_MEMBER_URL = "https://qyapi.weixin.qq.com/cgi-bin/user/delete";
	// 更新成员URL
	private final static String GET_DEPARTMENT_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/list";
	String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=wxbd7dc3e0680bf884&corpsecret=gWsp6EJqMdfY_I7HSFT5IfRwrjBXGNfLdq2tb5t0IAF5nkMFY5UsIiZi5Me2pAwa";
	// 获取接口访问权限码
	public static String getAccessToken() {		
		String requestUrl = ACCESS_TOKEN_URL + "?corpid=" + CORPID + "&corpsecret=" + CORPSECRET;
		JSONObject httpResult = HttpClientHelper.execHttpUrlJSON(requestUrl, null, false);
		String result = (String) httpResult.get("access_token");
		return result;
	}

	/**
	 * 企业接口向下属关注用户发送微信消息
	 *
	 * @param touser
	 *            成员ID列表（消息接收者，多个接收者用‘|’分隔，最多支持1000个）。特殊情况：指定为@all，
	 *            则向关注该企业应用的全部成员发送
	 * @param toparty
	 *            部门ID列表，多个接收者用‘|’分隔，最多支持100个。当touser为@all时忽略本参数	
	 * @param totag
	 *            标签ID列表，多个接收者用‘|’分隔。当touser为@all时忽略本参数
	 * @param content
	 *            消息内容
	 * @return
	 */
	public static String sendWeChatMessage(String ACCESS_TOKEN,String userID,String messageContext,String department) {
		String result = "";
		try{
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"touser\":" + "\"" + userID + "\",");
			sb.append("\"toparty\":" + "\"" + "" + "\",");
			sb.append("\"totag\":" + "\"" + "" + "\",");
			sb.append("\"msgtype\":" + "\"" + "text" + "\",");
			sb.append("\"agentid\":" + "\"" + "1" + "\",");
			sb.append("\"text\":" + "{");
			sb.append("\"content\":" + "\"" + messageContext + "\"},");
			sb.append("\"debug\":" + "\"" + "1" + "\"");
			sb.append("}");
			
			// 请求链接
			String url = CREATE_SESSION_URL + ACCESS_TOKEN;
			String contentType = "application/json;charset=UTF-8";
			String requestData = sb.toString();
			JSONObject jsonStr = HttpClientHelper.execHttpPostJSON(url, contentType, requestData);
	        result = jsonStr.getString("errcode");
		}catch(Exception e){
			log.error("发送微信消息出错",e);
		}
		return result;

	}

	/**
	 * 添加成员 要先获取部门所在的ID才知道要加在哪个部门
	 * 
	 * @param ACCESS_TOKEN
	 *            微信获取的有效权限
	 * @param userId
	 *            用户的在企业号的userId，必须唯一
	 * @param name
	 *            用户名
	 * @param department
	 *            创建成员所属的部门ID
	 * @param sex
	 *            创建成员的性别 1男 2女 0未定义
	 * @param email
	 *            weixinid mobile 邮箱 微信号 电话号 必须填写关注的微信号的3个信息中的一个
	 * 
	 */
	public static String addMember(String ACCESS_TOKEN, String userId, String name, List<Integer> department, String sex,
			String email, String weixinid, String mobile) {
		String result = "";
		try{
			StringBuffer sb = new StringBuffer();
			sb.append("{");
			sb.append("\"userid\":" + "\"" + userId + "\",");
			sb.append("\"name\":" + "\"" + name + "\",");
			sb.append("\"department\":"+department.toString()+",");
			sb.append("\"position\":" + "\"" + "" + "\",");
			sb.append("\"mobile\":" + "\"" + mobile + "\",");
			sb.append("\"gender\":" + "\"" + sex + "\",");
			sb.append("\"email\":" + "\"" + email + "\",");
			sb.append("\"weixinid\":" + "\"" + weixinid + "\",");
			sb.append("\"extattr\":" + "\"" + "" + "\",");
			// 请求链接
			String url = ADD_MEMBER_URL + ACCESS_TOKEN;
			String contentType = "application/json;charset=UTF-8";
			String requestData = sb.toString();
			JSONObject jsonStr = HttpClientHelper.execHttpPostJSON(url, contentType, requestData);
	        result = jsonStr.getString("errcode");
		}catch(Exception e){
			log.error("增加用户企业号出错",e);
		}
		return result;
	}

	/**
	 * 添加成员
	 * 
	 * @param ACCESS_TOKEN
	 *            微信获取的有效权限 必须
	 * @param userId
	 *            用户的在企业号的userId 必须
	 * @param name
	 *            用户名
	 * @param department
	 *            创建成员所属的部门ID
	 * @param sex
	 *            创建成员的性别
	 * @param email
	 *            weixinid mobile 邮箱 微信号 电话号
	 * 
	 */
	public static String updateMember(String ACCESS_TOKEN, String userId, String name, List<Integer> department, String sex,
			String email, String weixinid, String mobile) {
		//构造请求数据
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"userid\":" + "\"" + userId + "\",");
		sb.append("\"name\":" + "\"" + name + "\",");
		sb.append("\"department\":[3],");
		sb.append("\"position\":" + "\"" + "" + "\",");
		sb.append("\"mobile\":" + "\"" + mobile + "\",");
		sb.append("\"gender\":" + "\"" + sex + "\",");
		sb.append("\"email\":" + "\"" + email + "\",");
		sb.append("\"weixinid\":" + "\"" + weixinid + "\",");
		sb.append("\"extattr\":" + "\"" + "" + "\",");

		// 请求链接
		String result = "";
		String url = UPDATE_MEMBER_URL + ACCESS_TOKEN;
		String contentType = "application/json;charset=UTF-8";
		String requestData = sb.toString();
		JSONObject jsonStr = HttpClientHelper.execHttpPostJSON(url, contentType, requestData);
        result = jsonStr.getString("errcode");
		return result;
	}

	/**
	 * 删除成员
	 * 
	 * @param ACCESS_TOKEN
	 *            当前有效的权限
	 * @param userId
	 *            用户微信ID
	 * @return
	 */
	public static String deleteMember(String ACCESS_TOKEN, String userId) {
		String result = "";
		try{
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
	    	formparams.add(new BasicNameValuePair("access_token", ACCESS_TOKEN));
	    	formparams.add(new BasicNameValuePair("userid", userId));
	    	JSONObject httpResult = HttpClientHelper.execHttpUrlJSON(DELETE_MEMBER_URL,formparams,false);
			result = httpResult.getString("errcode");
			//60111代表用户不存在，认为是删除成功
			if("60111".equals(result))
			{
				result = "0";
			}
		}catch(Exception e){
			log.error("删除用户企业号出错",e);
		}
		return result;	
	}

	/**
	 * 获取部门ID
	 * 
	 * @param ACCESS_TOKEN
	 * @param id
	 * @param departmentName 部门名称
	 * @return
	 */
	public static String getDepartmentID(String ACCESS_TOKEN,String departmentName) {
		String result = null;
		try{
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
	    	formparams.add(new BasicNameValuePair("access_token", ACCESS_TOKEN));
	    	formparams.add(new BasicNameValuePair("id", CORPID));
	    	JSONObject resultJSON = HttpClientHelper.execHttpUrlJSON(GET_DEPARTMENT_URL, formparams, false);
			JSONArray resultJSONArray = resultJSON.getJSONArray("department");
			
			for(int i=0;i<resultJSONArray.size();i++)
			{
				if(resultJSONArray.getJSONObject(i).getString("name").equals(departmentName))
				{
					result = resultJSONArray.getJSONObject(i).getString("id");
					break;
				}
			}
		}catch(Exception e){
			log.error("获取部门ID出错",e);
		}
		return result;	
	}
	
	/**
	 * 判断成员是否已关注
	 * 
	 * @param ACCESS_TOKEN
	 * @param DEPARTMENT_ID 部门编号
	 * @param userID   企业用户ID 
	 * @return
	 */
	public static boolean isACUeser(String ACCESS_TOKEN, String DEPARTMENT_ID,String userID) {
		boolean result = false;
		try{
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
	    	formparams.add(new BasicNameValuePair("access_token", ACCESS_TOKEN));
	    	formparams.add(new BasicNameValuePair("department_id", DEPARTMENT_ID));
	    	formparams.add(new BasicNameValuePair("status", "1"));  //status=1 已关注的成员
	    	JSONObject resultJSON = HttpClientHelper.execHttpUrlJSON("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist", formparams, false);
			JSONArray resultJSONArray = resultJSON.getJSONArray("userlist");
			
			for(int i=0;i<resultJSONArray.size();i++)
			{
				if(resultJSONArray.getJSONObject(i).getString("userid").equals(userID))
				{
					result = true;
					break;
				}
			}
		}catch(Exception e){
			log.error("判断成员是否已关注出错",e);
		}
		return result;	
	}
	
	
	/**
	 * 判断成员是否已添加
	 * 
	 * @param ACCESS_TOKEN
	 * @param DEPARTMENT_ID 部门编号
	 * @param userID   企业用户ID 
	 * @return
	 */
	public static boolean isAAUeser(String ACCESS_TOKEN, String DEPARTMENT_ID,String userID) {
		boolean result = false;
		try{
			List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
	    	formparams.add(new BasicNameValuePair("access_token", ACCESS_TOKEN));
	    	formparams.add(new BasicNameValuePair("department_id", DEPARTMENT_ID));
	    	formparams.add(new BasicNameValuePair("status", "0"));  //status=1 全部成员
	    	JSONObject resultJSON = HttpClientHelper.execHttpUrlJSON("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist", formparams, false);
			JSONArray resultJSONArray = resultJSON.getJSONArray("userlist");
			
			for(int i=0;i<resultJSONArray.size();i++)
			{
				if(resultJSONArray.getJSONObject(i).getString("userid").equals(userID))
				{
					result = true;
					break;
				}
			}
		}catch(Exception e){
			log.error("判断成员是否已添加出错",e);
		}
		return result;	
	}
	
	
	/**
	 * 判断成员是否已添加
	 * 
	 * @param ACCESS_TOKEN
	 * @param DEPARTMENT_ID 部门编号
	 * @param userID   企业用户ID 
	 * @return
	 */
	public static boolean saveUserWCID(String S_USERID, String WECHATENTER_ID,String WECHAT_ID,String mobile,String email) {
		boolean result = false;
		try{   
			if((WECHAT_ID==null)||(WECHATENTER_ID==null))
			{
				return true;
			}
			
			if("null".equals(WECHAT_ID) || "null".equals(WECHATENTER_ID))
			{
				return true;
			}
			
			//null转换成""
			if("null".equals(mobile))
			{
				mobile = "";
			}
			
			if("null".equals(email))
			{
				email = "";
			}
			
			String accessToken = WeChatHelper.getAccessToken();
			String departmentID = WeChatHelper.getDepartmentID(accessToken, "报警推送");
			
			//判断是否是新建账户。 新建账户:直接添加微信企业号 .已有账号:对原先的进行删除
			String sql = "select * from safe_user where S_USERID = @S_USERID";
			List<GlobalParameter> pc = new ArrayList<>();
			pc.add(new GlobalParameter("S_USERID", S_USERID));
			//已有账户，编辑保存，需查看微信企业号ID有没有变更，若有，则调用接口，更新企业号用户，若无，则直接返回TRUE
			if(DataUtil.getSelectRows(sql, pc).size() > 0)
			{
				sql = "select * from safe_user where S_USERID = '"+S_USERID+"' and nvl(WECHATENTER_ID,-1) != '"+WECHATENTER_ID+"' ";
				List<RowBase> rows = DataUtil.getSelectRows(sql, null);
				if(rows.size()>0){
					RowBase row = rows.get(0);
					String oldWCEnteID = row.getSafeString("WECHATENTER_ID");
					//删除原先的企业ID
					if(!"0".equals(deleteMember(accessToken,oldWCEnteID))){
						return false;
					}   
					//判断WECHAT_ID是否为空，若为空，则直接删除即可
					if("".equals(WECHAT_ID))
					{
						return true;
					}
					//添加微信企业号
					List<Integer> department = new ArrayList<Integer>();
					department.add(Integer.valueOf(departmentID));	
					if(!"0".equals(addMember(accessToken,WECHATENTER_ID,"username",department,"1",email,WECHAT_ID,mobile))){
						return false;
					}
				}
			}else{
				//新建账户
				//判断WECHAT_ID是否为空，若为空，则不进行企业号的添加
				if("".equals(WECHAT_ID))
				{
					return true;
				}
				//添加微信企业号
				List<Integer> department = new ArrayList<Integer>();
				department.add(Integer.valueOf(departmentID));	
				if(!"0".equals(addMember(accessToken,WECHATENTER_ID,"username",department,"1",email,WECHAT_ID,mobile))){
					return false;
				}
			}

			result = true;
			
		}catch(Exception e){
			log.error("保存成员微信ID出错",e);
		}
		return result;	
	}
}
